# -*- coding: utf-8 -*-
from odoo.addons import decimal_precision as dp
from odoo.exceptions import AccessDenied, AccessError, UserError, ValidationError
from passlib.context import CryptContext
import logging
from odoo import api, http, models,fields,_,SUPERUSER_ID
from odoo.http import request
from odoo.tools import file_open, image_process, ustr
from odoo.tools.misc import str2bool
import re
import odoo.addons.decimal_precision as dp
import pytz
_logger = logging.getLogger(__name__)
# import numpy as np
import psycopg2
import time
# from bluetooth import *
import json
import base64

#继承这个类，增加env_company
# class Http(models.AbstractModel):
#     _inherit = 'ir.http'

#     def session_info(self):
#         user = self.env.user
#         session_uid = request.session.uid
#         version_info = odoo.service.common.exp_version()

#         if session_uid:
#             user_context = dict(self.env['res.users'].context_get())
#             if user_context != request.session.context:
#                 request.session.context = user_context
#         else:
#             user_context = {}

#         IrConfigSudo = self.env['ir.config_parameter'].sudo()
#         max_file_upload_size = int(IrConfigSudo.get_param(
#             'web.max_file_upload_size',
#             default=128 * 1024 * 1024,  # 128MiB
#         ))
#         mods = odoo.conf.server_wide_modules or []
#         if request.db:
#             mods = list(request.registry._init_modules) + mods
#         session_info = {
#             # "proto_id":user.proto_id.id, #dbh 增加的与扳手通讯的协议
#             "env_company":user.company_id.name,#dbh 增加的当前登录用户的公司名 
#             "uid": session_uid,
#             "is_system": user._is_system() if session_uid else False,
#             "is_admin": user._is_admin() if session_uid else False,
#             "user_context": user_context,
#             "db": self.env.cr.dbname,
#             "server_version": version_info.get('server_version'),
#             "server_version_info": version_info.get('server_version_info'),
#             "support_url": "https://www.odoo.com/buy",
#             "name": user.name,
#             "username": user.login,
#             "partner_display_name": user.partner_id.display_name,
#             "company_id": user.company_id.id if session_uid else None,  # YTI TODO: Remove this from the user context
#             "partner_id": user.partner_id.id if session_uid and user.partner_id else None,
#             "web.base.url": IrConfigSudo.get_param('web.base.url', default=''),
#             "active_ids_limit": int(IrConfigSudo.get_param('web.active_ids_limit', default='20000')),
#             'profile_session': request.session.profile_session,
#             'profile_collectors': request.session.profile_collectors,
#             'profile_params': request.session.profile_params,
#             "max_file_upload_size": max_file_upload_size,
#             "home_action_id": user.action_id.id,
#             "cache_hashes": {
#                 "translations": self.env['ir.http'].sudo().get_web_translations_hash(
#                     mods, request.session.context['lang']
#                 ) if session_uid else None,
#             },
#             "currencies": self.sudo().get_currencies(),
#             'bundle_params': {
#                 'lang': request.session.context['lang'],
#             },
#         }
#         if request.session.debug:
#             session_info['bundle_params']['debug'] = request.session.debug
#         if self.env.user.has_group('base.group_user'):
#             # the following is only useful in the context of a webclient bootstrapping
#             # but is still included in some other calls (e.g. '/web/session/authenticate')
#             # to avoid access errors and unnecessary information, it is only included for users
#             # with access to the backend ('internal'-type users)
#             menus = self.env['ir.ui.menu'].load_menus(request.session.debug)
#             ordered_menus = {str(k): v for k, v in menus.items()}
#             menu_json_utf8 = json.dumps(ordered_menus, default=ustr, sort_keys=True).encode()
#             session_info['cache_hashes'].update({
#                 "load_menus": hashlib.sha512(menu_json_utf8).hexdigest()[:64], # sha512/256
#             })
#             session_info.update({
#                 # current_company should be default_company
#                 "user_companies": {
#                     'current_company': user.company_id.id,
#                     'allowed_companies': {
#                         comp.id: {
#                             'id': comp.id,
#                             'name': comp.name,
#                             'sequence': comp.sequence,
#                         } for comp in user.company_ids
#                     },
#                 },
#                 "show_effect": True,
#                 "display_switch_company_menu": user.has_group('base.group_multi_company') and len(user.company_ids) > 1,
#             })
#         # self.dbh_update_work()    
#         return session_info

# class Users(models.Model):
#     _inherit="res.users"
#     user_id=fields.Integer('用户ID')
#     company_id = fields.Many2one('res.company', string='Company',ondelete='cascade')
# class Company(models.Model):
#     _inherit = "res.company"
#     co_id=fields.Integer('公司ID')    
class MeasCtlWorkMain(models.Model):
    _name="meas.ctl.work.main"
    _description="工单表头"
    _rec_name="name"
    _order="sequence"

    main_id=fields.Integer(string='工序单号')
    meas_id=fields.Char(string='工程单号')
    name = fields.Char(string="工序单名称")
    title=fields.Char(string='工序名称')
    # number=fields.Char('工序号',compute="_compute_number",store=True)
    require=fields.Text('工艺要求')    
    sequence=fields.Integer('序列号')
    work_sub_ids=fields.One2many('meas.ctl.work.sub','work_main_id',string='工单明细')
    company_id = fields.Many2one('res.company',string="组织",index=True,ondelete='cascade')
    # operator_id = fields.Many2one('res.users', default=lambda self: self.env.user.id)
    operator_id = fields.Many2one('res.users',string='操作员')
    # document_data1 = fields.Binary(string='附件1', attachment=True)
    # document_fname1 = fields.Char('附件1名', index=True)
    # document_data2 = fields.Binary(string='附件2', attachment=True)
    # document_fname2 = fields.Char('附件2名', index=True)
    # document_data3 = fields.Binary(string='附件3', attachment=True)
    # document_fname3 = fields.Char('附件3名', index=True)
    # document_data4 = fields.Binary(string='附件4', attachment=True)
    # document_fname4 = fields.Char('附件4名', index=True)
    document_image=fields.Image(string="图片文件",max_width=200,max_height=200)
    ref=fields.Char('工艺卡文件')
    prd_id=fields.Char('机号')
    prd_num=fields.Char(string='工程编号')
    prd_name=fields.Char(string='机型')
    # tool_id=fields.Many2one('meas.ctl.tool.info',string='选用量具')
    tool_ids=fields.Many2many('meas.ctl.tool.info',string='选用量具')
    no_pass=fields.Boolean("不放行")
    signature=fields.Image(string="签字")
    key=fields.Boolean('关键标识')
    key_image=fields.Binary(string="关键标识图",attachment=True)
    barcodestr=fields.Char('二维码字符串')
    no_tools=fields.Boolean('未选量具',compute="_compute_no_tools")
    choosed=fields.Boolean('未扫描选择过量具',default=False)
    permit_user_ids=fields.Many2many('res.users',string="允许操作人员")
    
    @api.depends('tool_ids','key')
    def _compute_no_tools(self):
        for r in self:
            if not r.key:
                r.choosed=True
            r.no_tools=not (bool(len(r.tool_ids)) and r.choosed) #有件且又选了=False
    
    @api.onchange('barcodestr')
    def _onchange_barcodestr(self):
        #当扫码的数据最后一位是},即可进行处理。否则需要加;等待下一个二维码
        if self.barcodestr[-1]=="}":
            com=self.env['meas.ctl.tool.info'].search([('tool_id','!=',False),('company_id','=',self.env.company.id)])
            tool_id2id=dict(zip(com.mapped('tool_id'),com.ids))
            barcode=self.barcodestr.split(';')
            id_list=[]
            for d in barcode:
                try:
                    data=json.loads(d)
                except:
                    raise ValidationError('分割符不是英文的;!')    
                if self.key:
                    if data['key'] and len(self.env['meas.ctl.tool.info'].search([('tool_id','=',data['id'])]))!=0:
                        id_list.append(int(data['id']))
                else:
                    if not data['key'] and len(self.env['meas.ctl.tool.info'].search([('tool_id','=',data['id'])]))!=0:
                        id_list.append(int(data['id']))        
            self_tool_id_list=[tool_id2id[t] for t in id_list]            
            self.tool_ids=[(6,0,self_tool_id_list)]
            self.barcodestr=None
            self.choosed=True #表示已经选择过量具了，而非初始状态显示工序配置的量具信息
        pass

    # def match(self):
    #     while(True):
    #         self.findDevs()
    #         time.sleep(5)

    # def findDevs(self):
    #     alreadyFound = []
    #     foundDevs = discover_devices(lookup_names=True)
    #     # 循环遍历,如果在列表中存在的就不打印
    #     for (addr,name) in foundDevs:
    #         if addr not in alreadyFound:
    #             print("[*]蓝牙设备:" + str(name))
    #             print("[+]蓝牙MAC:" + str(addr))
    #             # 新增的设备mac地址定到列表中,用于循环搜索时过滤已打印的设备
    #             alreadyFound.append(addr)




    #启动这个模型，修改字段的属性
    @api.model
    def fields_get(self,allfields=None,attributes=None):
        res = super(MeasCtlWorkMain, self).fields_get(allfields=allfields,attributes=attributes)
        #判断当前登录用户是否是管理员，如果不是则将其字段改成自读属性，否则可以修改其放行
        if 'no_pass' in res:
            if not self.user_has_groups('meas_ctl.group_meas_ctl_pass'):
                res['no_pass']['readonly']=True
            else:
                res['no_pass']['readonly']=False    
        return res

    def dbh_update_work(self):
        #获取tools的信息
        company_id=self.env['res.company'].search([('id','=',self.env.company.id)]).mapped('co_id')[0]
        if not company_id:
            raise ValidationError('当前用户所属组织与服务器中的组织不匹配！')
        # domain=[('company_id','=',company_id)]
        domain=[]
        fields=[]
        tools=self.env['meas.ctl.rpc'].fetch_data(domain,'meas.tool.info',fields)
        # tool_ids=self.env['meas.ctl.tool.info'].search([('tool_id','!=',False),('company_id','=',self.env.company.id)]).mapped('tool_id')
        tool_ids=self.env['meas.ctl.tool.info'].search([])
        tool_ids.sudo().unlink()
        for t in tools:
            # if t['id'] not in tool_ids:
            self.env['meas.ctl.tool.info'].sudo().create({
                'deviceID':t['deviceID'],
                'name':t['name'],
                'partno':t['partno'],
                'tool_id':t['id'],
                'proto':t['proto'],
                'key':t['key'],
                'barcode':t['barcode'],
                # 'company_id':self.env['res.company'].search([('co_id','=',t['company_id'][0])]) and self.env['res.company'].search([('co_id','=',t['company_id'][0])]).id
                'company_id':self.env['res.company'].sudo().search([('co_id','=',t['company_id'][0])]).id
            })
        # 获取服务器tool.info与本地的对应列表        
        # com=self.env['meas.ctl.tool.info'].search([('tool_id','!=',False),('company_id','=',self.env.company.id)])
        com=self.env['meas.ctl.tool.info'].sudo().search([('tool_id','!=',False)])
        tool_id2id=dict(zip(com.mapped('tool_id'),com.ids))
        users=self.env['res.users'].sudo().search([('user_id','!=',False)])
        user_id2id=dict(zip(users.mapped('user_id'),users.ids))
        #获取work_sub的信息
        company_id=self.env['res.company'].search([('id','=',self.env.company.id)]).mapped('co_id')[0]
        if not company_id:
            raise ValidationError('当前用户所属组织与服务器中的组织不匹配！')
        #只获取当前组织对应的服务器该组织的工单数据
        domain=[('company_id','=',company_id)]
        fields=[]
        work_sub=self.env['meas.ctl.rpc'].fetch_data(domain,'meas.work.sub',fields)
        work_main=self.env['meas.ctl.rpc'].fetch_data(domain,'meas.work.main',fields)
        self_work_main_id_list=self.env['meas.ctl.work.main'].search([]).mapped('main_id')
        for wm in work_main:
            if wm['main_id'][0] not in self_work_main_id_list:
                company_id=self.env['res.company'].search([('co_id','=',wm['company_id'][0])]) and self.env['res.company'].search([('co_id','=',wm['company_id'][0])]).id
                nw=self.env['meas.ctl.work.main'].sudo().create({
                    'main_id':wm['main_id'][0],
                    'meas_id':wm['meas_id'][1],
                    'name':wm['name'],
                    'title':wm['title'],
                    'require':wm['require'],
                    'company_id':company_id,
                    'document_image':wm['document_image'],
                    'ref':wm['ref'],
                    'tool_ids':[(6,0,[tool_id2id.get(t,False) for t in wm['ref_tool_ids']])],
                    'permit_user_ids':[(6,0,[user_id2id.get(t,False) for t in wm['permit_user_ids']])],
                    'prd_id':wm['prd_id'][1],
                    'prd_name':wm['prd_name'],
                    'prd_num':wm['prd_num'], 
                    'key':wm['key'],
                    'key_image':wm['key_image']
                    # 'signature':wm['signature']
                })
                # 查找meas.work.sub.meas_main_id==meas.work.main.main_id
                # w_sub=self.env['meas.ctl.rpc'].find_dict_by_value(work_sub,'meas_main_id',wm['main_id'])
                # 查找meas.work.sub.meas_main_id==meas.work.main.id
                w_sub=self.env['meas.ctl.rpc'].find_dict_by_value(work_sub,'work_main_id',wm['id'])
                for w in w_sub:
                    self.env['meas.ctl.work.sub'].sudo().create({
                        'company_id':company_id,
                        'work_main_id':nw.id, #设置工单表头的id，
                        'meas_main_sub_id':w['meas_main_sub_id'][0],
                        'meas_main_id':w['meas_main_id'][0],
                        'number':w['number'],
                        'worktype_selection':w['worktype_selection'],
                        'position_id':w['position_id'][1],
                        'target_value':w['target_value'],
                        'value_unit':w['value_unit'],
                        'min_value':w['min_value'],
                        'max_value':w['max_value'],
                        'allow':w['allow'],
                        'target_value2':w['target_value2'],
                        'min_value2':w['min_value2'],
                        'max_value2':w['max_value2'],
                        'allow2':w['allow2'],
                        'remark':w['remark'],
                        'decimal':w['decimal'],
                        # 'result':w['result'],
                        # 'check':w['check'],
                        # 'real_value':w['real_value'],
                        # 'real_value2':w['real_value2'],
                        'worktype_value':w['worktype_value'],
                        'grp':w['grp'],
                        'sequence':w['sequence'],
                        # 'photo':w['photo'],
                    })
        return
        # self_main_sub_id_list=self.env['meas.ctl.work.sub'].search([]).mapped('meas_main_sub_id') 
        # for w in work_sub:
        #     # if w['meas_main_sub_id'][0] not in self_main_sub_id_list:
        #     if w['meas_main_sub_id'][0]:
        #         company_id=self.env['res.company'].search([('co_id','=',w['company_id'][0])]) and self.env['res.company'].search([('co_id','=',w['company_id'][0])]).id
        #         nw=self.env['meas.ctl.work.sub'].create({
        #             'meas_main_sub_id':w['meas_main_sub_id'][0],
        #             'number':w['number'],
        #             'item':w['item_id'][1],
        #             'worktype_selection':w['worktype_selection'],
        #             'position':w['position_id'][1],
        #             'sequence':w['sequence'],
        #             'target_value':w['target_value'],
        #             'value_unit':w['value_unit'],
        #             'min_value':w['min_value'],
        #             'max_value':w['max_value'],
        #             'allow':w['allow'],
        #             'remark':w['remark'],
        #             'dispatch':w['dispatch'],
        #             'dispatched':w['dispatched'],
        #             'worktype_value':w['worktype_value'],
        #             'require':w['require'],
        #             'ref':w['ref'],
        #             'document_image':w['document_image'],
        #             'meas_id':w['meas_id'][0],
        #             'meas_name':w['meas_id'][1],
        #             'meas_number':w['meas_number'],
        #             'meas_name':w['meas_name'],
        #             'company_id':company_id,
        #             'tool_id':tool_id2id.get(w['tool_id'] and w['tool_id'][0],False)
        #         })
        # return    

    def upto_meas_data(self):
        id_user_dict=self.dbh_get_user_id_rel()
        id_tool_dict=self.dbh_get_tool_id_rel()
        active_list=self.env.context.get('active_ids',self.ids)
        active_model=self.env.context.get('active_model',self._name)
        # active_model : meas.ctl.work.main
        company_id=self.env.company.id
        #工单选中后动作中会出现上传数据，下面获取已经通个的所有数据并建立字典列表,在meas.data执行create创建数据：
        records=self.env[active_model].search([('id','in',active_list),('no_pass','=',False),('company_id','=',company_id)])
        # records_sub=records.work_sub_ids
        vals_list=[]    
        for r in records:    
            for rec in r.work_sub_ids:
                #将本地的user_id传换成服务器对应的user_id
                #采集数据的登录用户一定是服务器存在的用户，否则上传数据后的用户就不匹配了
                user_id=id_user_dict.get(rec.operator_id.id,False)
                if not user_id:
                    raise ValidationError('操作人员与服务器不相符！')
                #解决json不能直接传二进制文件
                if r.signature:
                    signature=str(base64.b64encode(r.signature),'utf-8')
                else:
                    signature=None    
                if rec.photo:
                    photo=str(base64.b64encode(rec.photo),'utf-8')
                else:
                    photo=None    
                vals_list.append({
                'meas_main_sub_id':rec.meas_main_sub_id,
                'operator_id':user_id,
                'company_id':self.env['res.company'].browse(r.company_id.id).co_id,
                'datetime_work':str(rec.datetime_work) or str(fields.Datetime.now()),
                'result':rec.result,
                'check':rec.check,
                'real_value':rec.real_value,
                'real_value2':rec.real_value2,
                'tool_ids':[(6,0,[id_tool_dict.get(t,'') for t in r.tool_ids.ids])],
                'meas_main_id':r.main_id,
                'signature':signature,
                'photo':photo,
                'permit_user_ids':[(6,0,[id_user_dict.get(t,False) for t in r.permit_user_ids.ids])],

                })
        result=self.env['meas.ctl.rpc'].operation_create('meas.data',vals_list)
        if not result:
            records.sudo().unlink()
        else:
            raise ValidationError(result['message'])
        return
    def dbh_get_user_id_rel(self):
        # 创建user的服务器端与客户端id对应字典.id_user->user_id
        com=self.env['res.users'].sudo().search([('user_id','!=',False)])
        id_dict=dict(zip(com.ids,com.mapped('user_id')))
        return id_dict
    def dbh_get_tool_id_rel(self):
        # 创建company的服务器端与客户端id对应字典
        com=self.env['meas.ctl.tool.info'].search([('tool_id','!=',False)])
        id_tool_dict=dict(zip(com.ids,com.mapped('tool_id')))
        return id_tool_dict
        # vals_list=[]    
        # for r in records:    
        #     for rec in r.work_sub_ids:
        #         vals_list.append({
        #         'meas_main_sub_id':rec.meas_main_sub_id.id,
        #         'operator_id':rec.operator_id.id,
        #         'datetime_work':rec.datetime_work or fields.Datetime.now(),
        #         'result':rec.result,
        #         'check':rec.check,
        #         'real_value':rec.real_value,
        #         'real_value':rec.real_value2,
        #         'tool_id':rec.tool_id.id,
        #         'meas_main_id':r.main_id.id
        #         })
        # self.env['meas.data'].create(vals_list)    
        # return

class MeasCtlWorkSub(models.Model):
    _name="meas.ctl.work.sub"
    _description="工单"
    _rec_name="number"
    # _order="sequence"

    work_main_id=fields.Many2one('meas.ctl.work.main',ondelete='cascade')
    datetime_work=fields.Datetime('操作时间',default=fields.Datetime.now())
    meas_main_sub_id=fields.Integer(string="工序节点号")
    meas_main_id=fields.Integer(string='工序单号')
    number = fields.Char('节点')
    worktype_selection=fields.Char(string='类型')
    position_id=fields.Char(string='位置')
    sequence=fields.Integer(string='顺序号')
    target_value=fields.Float(string="目标值(3位)",digits='Meas of Unit')
    # value_unit=fields.Selection(string='单位')
    value_unit=fields.Char(string='单位')
    min_value=fields.Float(string='最小值(3位)',digits='Meas of Unit')
    max_value=fields.Float(string='最大值(3位)',digits='Meas of Unit')
    allow=fields.Float(string='误差范围(3位):',digits='Meas of Unit')
    target_value2=fields.Float(string="目标值(2位)",digits='two of Unit')
    min_value2=fields.Float(string='最小值(2位)',digits='two of Unit')
    max_value2=fields.Float(string='最大值(2位)',digits='two of Unit')
    allow2=fields.Float(string='误差范围(2位):',digits='two of Unit')
    remark=fields.Char("说明")
    operator_id = fields.Many2one('res.users',string='操作员')
    company_id = fields.Many2one('res.company',string="组织",index=True,ondelete='cascade')
    decimal=fields.Boolean('小数点三位')
    result=fields.Text('自定义输入')
    check=fields.Boolean('判断检测')
    compute_ids=fields.One2many('meas.ctl.compute','work_id',string='运算数据')
    real_value=fields.Float('实测数据(3位)',digits="Meas of Unit")
    real_value2=fields.Float('实测数据(2位)',digits="two of Unit")
    # tool_id=fields.Many2one('meas.ctl.tool.info',string='所用工具:',related="work_main_id.tool_id",store=True)
    worktype_value=fields.Char('导出数据显示值')
    require=fields.Text('工艺要求',related="work_main_id.require")
    ref=fields.Char('工艺卡文件',related="work_main_id.ref")
    document_image=fields.Image(string="图片文件",max_width=200,max_height=200,related="work_main_id.document_image")
    # meas_id=fields.Many2one('meas.meas',string='工程号',related='meas_main_sub_id.meas_id')
    prd_name=fields.Char('机型',related="work_main_id.prd_name")
    no_pass=fields.Boolean('不放行',compute="_compute_no_pass",store=True)
    prd_id=fields.Char(string='机号',related="work_main_id.prd_id")
    prd_num=fields.Char(string='工程编号',related="work_main_id.prd_name")
    grp=fields.Selection([('#1','#1'),('#2','#2'),('#3','#3'),('#4','#4'),('#5','#5'),('#6','#6'),
                          ('#7','#7'),('#8','#8'),('#9','#9'),('0',' ')],string='组')
    # signature=fields.Image(string="签字",related="work_main_id.signature",store=True)
    photo=fields.Image(string="照片")
    key=fields.Boolean('关键标识',related="work_main_id.key",store=True)
    key_image=fields.Binary(string="关键标识图",attachment=True,related="work_main_id.key_image")
    no_tools=fields.Boolean('未选量具',related="work_main_id.no_tools")


    def collect_action(self):
        action = {
                'name': '采集数据',
                'res_model': 'meas.ctl.work.sub.wizard',
                'type': 'ir.actions.act_window',
                'view_mode': 'form',
                'views': [[self.env.ref('meas_ctl.collection_form_wizard').id, 'form']],
                'target': 'new',
            }
        return action    
    @api.depends('real_value','real_value2','result','check')
    def _compute_no_pass(self):
        work_main_id=self.work_main_id
        no_pass_list=[]
        ids=work_main_id.work_sub_ids.ids
        for i in ids:
            r=self.env['meas.ctl.work.sub'].browse(i)
            r.no_pass=True
            if r.worktype_selection == 'A1' and r.operator_id and not r.no_tools:
                if r.real_value:
                    if r.real_value >= r.min_value and r.real_value <=r.max_value:
                        r.no_pass=False
                    else:
                        r.no_pass=True
                elif r.real_value2:
                    if r.real_value2 >= r.min_value2 and r.real_value2 <=r.max_value2:
                        r.no_pass=False
                    else:
                        r.no_pass=True

            if r.worktype_selection == 'A2':
                    r.no_pass=not r.operator_id    
            if r.worktype_selection == 'A3' and r.operator_id:
                if r.result:
                    r.no_pass=False
                else:
                    r.no_pass=True
            if r.worktype_selection == 'A4' and r.operator_id and not r.no_tools:
                # if r.compute >= r.min_value and r.compute <= r.max_value:
                if r.real_value:
                    if r.real_value >= r.min_value and r.real_value <= r.max_value:
                        r.no_pass=False
                    else:
                        r.no_pass=True
                elif r.real_value2:
                    if r.real_value2 >= r.min_value2 and r.real_value2 <= r.max_value2:
                        r.no_pass=False
                    else:
                        r.no_pass=True
            no_pass_list.append(r.no_pass)
        work_main_id.no_pass=any(no_pass_list)    
        return

    def write(self,val):
        val['operator_id']=self.env.user.id
        val['datetime_work']=fields.Datetime.now()
        super().write(val)
    
    @api.depends("compute_ids")
    def _compute_compute(self):
        for r in self:
            if r.worktype_selection == 'A4' and r.compute_ids:
                i=0
                value=0.000
                for rec in r.compute_ids:
                    if rec.value != 0:
                        i=i+1
                        value= value + rec.value
                if i !=0:        
                    # r.compute=value/i
                    r.real_value=value/i
                else:
                    # r.compute=0
                    r.real_value=0
            # else:
            #     r.compute=0        

class MeasCtlCompute(models.TransientModel):
    _name="meas.ctl.compute"
    _description="采集多数据"

    value=fields.Float('采集值',digits="Meas of Unit",default=False)
    work_id=fields.Many2one('meas.ctl.work.sub',string="工单")
    company_id = fields.Many2one('res.company',string="组织",default=lambda self:self.env.user.company_id.id)
class CtlToolInfo(models.Model):
    _name="meas.ctl.tool.info"
    _description='工具信息'
    # _sql_constraints = [
    # ('deviceID_uniq',
    # 'UNIQUE (deviceID,company_id)',
    # '量具ID不能重复!')
    # ]

    deviceID=fields.Char('量具ID')
    name=fields.Char('量具名称',required="1")
    partno=fields.Char('量具型号')
    company_id = fields.Many2one('res.company',string="组织",ondelete="cascade")
    proto= fields.Selection([('ariter','Ariter'),('bluetork','bluetork')],default='ariter',string="通讯协议")
    tool_id=fields.Integer('服务器对于的工具ID')
    # work_ids=fields.One2many('meas.ctl.work.sub','tool_id',string='关联的工单')
    key=fields.Boolean('关键标识')
    barcode=fields.Char('二维码')

    def name_get(self):
        rec=[]
        for r in self:
            rec.append((r.id,'%s%s' % (r.name,r.partno and '('+r.partno+')' or '')))
        return rec    
